<template>
  <div style="width: 100vw; display: flex; justify-content: center; background: #F9F9F9">
    <div class="container" style="width: 75vw">
      <!-- 导航栏 -->
      <StuAssignmentNavBar :homeworkId="homeworkId" :semesterId="semesterId" />
      <!-- 错误提示 -->
      <div v-if="errorMessage" class="error-message">
        <p>{{ errorMessage }}</p>
      </div>
      <!-- 学生作业情况表格 -->
      <div class="student-table-section">
        <table class="student-table">
          <thead>
            <tr>
              <th>学号</th>
              <th>用户名</th>
              <th>完成状态</th>
              <th>得分</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <template v-for="(student, index) in filteredAssignments" :key="student.stu_hmwk_id || index">
              <!-- 基本信息行 -->
              <tr>
                <td>{{ student.stu_number || '--' }}</td>
                <td>{{ student.username }}</td>
                <td :class="getSubmitStatusClass(student.status)">
                  {{ getSubmitStatus(student.status) }}
                </td>
                <td class="score">{{ student.getscore || '--' }}</td>
                <td>
                  <!-- 移除查看按钮 -->
                </td>
              </tr>
              <!-- 详细信息行 -->
              <tr>
                <td colspan="5">
                  <div class="student-details">
                    <!-- 得分横幅 -->
                    <div class="score-banner">
                      <span class="score-value">{{ student.getscore || '--' }}</span>分= 
                      <span>
                        教师评分: <span class="score">{{ student.hmk_score_detail?.techScore || '__' }}</span>*<span class="percentage">{{ student.hmk_score_detail?.tech_weight || '--' }}</span>% 
                        + 助教评分: <span class="score">{{ student.hmk_score_detail?.adminScore || '__' }}</span>*<span class="percentage">{{ student.hmk_score_detail?.admin_weight || '--' }}</span>% 
                        + 互评评分: <span class="score">{{ student.hmk_score_detail?.stuScore || '__' }}</span>*<span class="percentage">{{ student.hmk_score_detail?.each_weight || '--' }}</span>% 
                        - 补交扣分: <span class="score">{{ student.hmk_score_detail?.remit_score || '__' }}</span> 
                        - 缺评扣分: <span class="score">{{ student.hmk_score_detail?.each_score || '__' }}</span>
                      </span>
                    </div>
                    <!-- 题目 -->
                    <div class="question-section">
                      <h3>题目：</h3>
                      <div v-html="student.question || '--'"></div>
                    </div>
                    <!-- 作答内容 -->
                    <div class="answer-attachment-container">
                      <template v-if="canOperate && (!isSubmit || isEditing)">
                        <!-- 编辑态：首次提交或正在修改 -->
                        <div class="answer-section">
                          <h3>作答内容：</h3>
                          <QuillEditor v-model="formData.content" />
                        </div>
                        <div class="attachment-section">
                          <h3>附件：</h3>
                          <div class="upload-container">
                            <label class="upload-button">
                              <input type="file" @change="handleFileUpload" hidden>
                              <span class="upload-icon">📎</span>
                              选择文件
                            </label>
                          </div>
                          <div class="inline">
                            <button @click="submitAssignment" class="submit-button">
                              <span class="submit-icon">{{ isEditing ? '提交修改' : '提交作业' }}</span> 
                            </button>
                            <p v-if="formData.attachment_url" class="upload-success">
                              <a class="success-icon" :href="formData.attachment_url" target="_blank">✔上传成功!</a> 
                            </p>
                          </div>
                        </div>
                      </template>

                      <template v-else>
                        <!-- 查看态 -->
                        <div class="answer-section">
                          <h3>作答内容：</h3>
                          <div v-html="student.content || '--'"></div>
                        </div>
                        <div class="attachment-section">
                          <h3>附件：</h3>
                          <div class="attachment-container">
                            <a v-if="student.attachment_url"
                              :href="student.attachment_url" target="_blank">
                              下载附件
                            </a>
                            <img v-else src="@/assets/picture/none.png" class="no-attachment-img" />
                          </div>
                          <!-- 修改按钮（仅在非编辑时出现） -->
                          <template v-if="!isEditing && hmkStatus !== '4'">
                            <button
                               v-if="canOperate && isSubmit && !isEditing"
                              @click="() => {
                                isEditing = true;
                                const current = studentAssignments[0];
                                formData.content = current?.content || '';
                                formData.attachment_url = current?.attachment_url || '';
                              }"
                              class="submit-button"
                              style="margin-top: 20px;"
                            >
                              <span class="submit-icon">修改作业</span>
                            </button>
                          </template>
                          <p
                            v-if="!canOperate && !isSubmit"
                            style="text-align:center;color:#888"
                          >
                            提交时间已过
                          </p>
                        </div>
                      </template>
                    </div>
                    <!-- 评阅列表 -->
                    <div class="comments-section">
                      <h3>评阅列表</h3>
                      <div v-for="(comment, cIndex) in student.comments" :key="cIndex" class="content-card">
                        <strong>{{ comment.username }} ({{ getIdentityLabel(comment.identity) }})：</strong>
                        <p v-html="comment.each_comment"></p>
                        <div class="comment-meta">
                          <span>评论时间: {{ comment.create_time }}</span>
                          <span>评阅分数: {{ comment.each_score ?? '未评分' }}</span>
                        </div>
                      </div>
                      <div v-if="student.comments.length === 0" class="no-comments">
                        <p>暂无评论</p>
                      </div>
                    </div>
                  </div>
                </td>
              </tr>
            </template>
            <tr v-if="filteredAssignments.length === 0">
              <td colspan="5" class="no-data">暂无数据</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { StuAssignment, StufetchStudentDetails, fetchComments, fetchAssignmentDetails,submitHomework,updateStudentAssignment } from '@/services/api'; // 保留原有接口
import StuAssignmentNavBar from '@/components/StuAssignmentNavBar.vue'; // 引入导航栏组件
import { uploadFile } from '@/services/api';
import QuillEditor from '@/components/QuillEditor.vue';


export default {
  name: 'StuAssignmentList',
  components: { StuAssignmentNavBar,QuillEditor },
  props: {
    homeworkId: {
      type: [String, Number],
      required: true,
    },
    semesterId: {
      type: [String, Number],
      required: true,
    },
  },
  setup(props) {
     const formData = ref({
      content: '',
      attachment_url: ''
    });
    const canOperate = computed(() => hmkStatus.value === '1' || hmkStatus.value === '2');
    const hmkStatus = ref(localStorage.getItem('hmk_status') || '0');
    const isEditing = ref(false); 
    const isSubmit = ref(localStorage.getItem('is_submit') === 'true');
    const studentAssignments = ref([]);
    const expandedStudent = ref(null); // 存储展开的学生作业详情
    const searchTerm = ref('');
    const errorMessage = ref('');
    const commentsErrorMessage = ref('');
    const comments = ref([]);
    const identity = ref(localStorage.getItem('identity') || null);
    const getIdentityLabel = (identity) => {
      switch (identity) {
        case '0': return '学生';
        case '1': return '老师';
        case '2': return '管理员';
        default: return '未知';
      }
    };
    const loadComments = async (stu_hmwk_id) => {
        try {
    if (!stu_hmwk_id) {
      throw new Error('缺少学生作业ID');
    }
    const response = await fetchComments(stu_hmwk_id);

        if (response.data.status === 1) {
          comments.value = response.data.data || []; // 确保为空数据时初始化为空数组
          commentsErrorMessage.value = ''; // 清空错误信息
        } else {
          commentsErrorMessage.value = `获取评论列表失败：${response.data.msg}`;
        }
      } catch (error) {
        commentsErrorMessage.value = '加载评论列表失败，请稍后重试。';
        comments.value = []; // 确保在错误发生时将评论初始化为空数组
      }
    };
    // 获取作业列表（使用原有接口）
     const loadStudentAssignments = async () => {
      try {
        const userId = localStorage.getItem('id');
        const response = await StuAssignment(userId, props.homeworkId);
        if (response.data.status === 1) {
          let assignments = Array.isArray(response.data.data) 
            ? response.data.data 
            : [response.data.data];
          
          // 获取题目内容
          const questionRes = await fetchAssignmentDetails(props.homeworkId);
          const assignmentContent = questionRes.data?.status === 1 
            ? questionRes.data.data.hmk_content 
            : '--';

          // 并行获取学生详细信息和评论
          const detailedStudents = await Promise.all(
            assignments.map(async (student) => {
              try {
                // 获取作业详情
                const detailRes = await StufetchStudentDetails(student.stu_hmwk_id);
                const details = detailRes.data.status === 1 ? detailRes.data.data : {};
                
                // 获取评论
                const commentsRes = await fetchComments(student.stu_hmwk_id);
                const comments = commentsRes.data.status === 1 
                  ? commentsRes.data.data 
                  : [];
                
                return {
                  ...student,
                  ...details,
                  question: assignmentContent,
                  comments,
                  commentsError: commentsRes.data.status === 1 ? '' : '加载评论失败'
                };
              } catch (error) {
                return {
                  ...student,
                  question: assignmentContent,
                  comments: [],
                  commentsError: '加载详情失败'
                };
              }
            })
          );
          
          studentAssignments.value = detailedStudents;
        }
      } catch (error) {
        // 错误处理...
      }
    };
    // 获取提交状态文本
    const getSubmitStatus = (status) => {
      switch (parseInt(status)) {
        case 0:
          return '未提交';
        case 1:
          return '按时提交';
        case 2:
          return '补交';
        default:
          return '--';
      }
    };

    // 获取提交状态类
    const getSubmitStatusClass = (status) => {
      const numStatus = parseInt(status);
      if (numStatus === 1) return 'submitted-on-time'; // 按时提交
      else if(numStatus === 2) return 'submitted-late';
      return 'not-submitted'; // 其他所有状态
    };

    const filteredAssignments = computed(() => {
      let filtered = studentAssignments.value;

      if (searchTerm.value.trim()!== '') {
        const term = searchTerm.value.trim().toLowerCase();
        filtered = filtered.filter(
          (student) =>
            (student.username && student.username.toLowerCase().includes(term)) ||
            (student.stu_number && student.stu_number.includes(term))
        );
      }

      return filtered;
    });
      // 文件上传处理
   const handleFileUpload = async (e) => {
  const file = e.target.files[0];
  if (file) {
    try {
      // 修复：使用正确的FormData结构
      const form = new FormData();
      form.append('file', file); 
      form.append('status', '2');  // 接口要求字符串类型
      
      // 调用修改后的上传方法
     const response = await uploadFile(file, 2);
      if (response.data.status === 1) {
        // 修改为直接使用response.data.data
        formData.value.attachment_url = response.data.data; 
        ElMessage.success('附件上传成功');
      } else {
        ElMessage.error('附件上传失败');
      }
    } catch (error) {
      ElMessage.error(`上传失败：${error.response?.data?.error || error.message}`);
    }
  }
};


    // 作业提交处理
    const submitAssignment = async () => {
      try {
        const userId = localStorage.getItem('id');
        const stuHmwkId = studentAssignments.value[0]?.stu_hmwk_id;

        if (isSubmit.value && isEditing.value) {
          // 修改作业接口
          const response = await updateStudentAssignment(
            stuHmwkId,
            formData.value.content,
            formData.value.attachment_url
          );
          if (response.data.status === 1) {
            isEditing.value = false;
            ElMessage.success('修改成功');
            await loadStudentAssignments();
          } else {
            ElMessage.error(`修改失败：${response.data.msg}`);
          }
        } else {
          // 首次提交接口
          const payload = {
            hmk_id: props.homeworkId,
            content: formData.value.content,
            attachment_url: formData.value.attachment_url,
            user_id: userId,
            is_remit: localStorage.getItem('hmk_status') === '2'
          };
          const response = await submitHomework(payload);
          if (response.data.status === 1) {
            localStorage.setItem('is_submit', 'true');
            isSubmit.value = true;
            ElMessage.success('提交成功');
            await loadStudentAssignments();
          } else {
            ElMessage.error(`提交失败：${response.data.msg}`);
          }
        }
      } catch (error) {
        ElMessage.error(`提交失败：${error.response?.data?.error || error.message}`);
      }
    };

    onMounted(() => {
      loadStudentAssignments(); // 获取作业列表
    });

    return {
      studentAssignments,
      expandedStudent,
      searchTerm,
      errorMessage,
      filteredAssignments,
      getSubmitStatus,
      getSubmitStatusClass,
      commentsErrorMessage,
      loadComments,
      comments,identity,
      getIdentityLabel,
      formData,
      isSubmit,
      handleFileUpload,
      submitAssignment,
      isEditing,
      hmkStatus,
      canOperate,
    };
  },
};
</script>



<style scoped>
.student-details {
  padding: 20px;
  background: #fff;
  border: 1px solid #eee;
  margin: 10px 0;
}

.comments-section {
  margin-top: 20px;
}

.comment-meta {
  display: flex;
  justify-content: space-between;
  font-size: 0.9em;
  color: #666;
}
* {
  font-family: Arial, sans-serif;
}

.container {
  width: 100vw;
  background: #F9F9F9;
  min-height: 100vh;
  padding: 20px;
  padding-top: 0px;
}

.error-message {
  background-color: #f8d7da;
  color: #721c24;
  padding-left: 30px;
  font-size: 14px;
  border: 1px solid #f5c6cb;
}

.student-table-section {
  background-color: #ffffff;
  padding: 20px 30px;
}

.search-input {
  padding: 8px 12px;
  margin-right: 10px;
  width: 250px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.search-button {
  padding: 8px 16px;
  background-color: #2f57a7;
  color: white;
  border: none;
  cursor: pointer;
  border-radius: 4px;
}

.search-button:hover {
  background-color: #2a4d8f;
}

.student-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

.student-table th,
.student-table td {
  padding: 12px;
  text-align: left;
  font-family: inherit;
}

.student-table th {
  background-color: #f6f7f9;
  color: #535353;
  font-size: 14px;
}

.student-table td.view-button {
  color: #1e90ff;
  border: 1px solid #1e90ff;
  padding: 5px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.student-table td.view-button:hover {
  background-color: #c5e2ff;
}
.score{
  color: #D5873A
}
.student-table.score {
  color: #009900;
}

.submitted-on-time {
  color: #28a745 !important; /* 绿色 */
}
.submitted-late {
  color: orange !important; 
}

.not-submitted {
  color: #dc3545 !important; /* 红色 */
}
.student-details {
  background-color: #f6f7f9;
  padding: 20px;
  margin-top: 10px;
  border-radius: 8px;
}

.no-data {
  text-align: center;
  padding: 20px;
  font-size: 16px;
}

.score-banner {
  background-color: #f9f1e7;
  padding: 10px;
  border-radius: 5px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.score-value {
  font-size: 24px;
  font-weight: bold;
  margin-right: 10px;
  color: #009900;
}

.score-composition {
  display: flex;
  flex-wrap: wrap;
  font-size: 12px;
  line-height: 1.2; 
}

.score-composition span {
  /* 减少span之间的右边距 */
  margin-right: 2px; 
}

.score-composition span :where([data-testid^="score"]),
.score-composition span :where([data-testid^="percentage"]) {
  color: orange;
}

/* 进一步调整内容之间的间距，比如运算符和数字之间的间距 */
.score-composition span:not(:last-child):after {
  content: "";
  /* 这里根据实际情况调整宽度，减少间距 */
  margin-left: 2px; 
}
.question-section,
.answer-section {
  margin-bottom: 10px;
  background-color: #fff;
  padding: 10px;
  border-radius: 5px;
}

.question-section h3,
.answer-section h3 {
  margin-top: 0;
}

.answer-attachment-container {
  display: flex;
  margin-bottom: 12px;
}
.answer-section {
  flex: 3; /* 内容部分占比更多，这里设置为3份 */
  background-color: #fff;
  padding: 10px;
  border-radius: 5px;
}
.attachment-section {
  margin-left: 40px;
  flex: 1; /* 附件部分占比1份 */
  padding: 10px;
  border-radius: 5px;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  overflow: hidden;
  flex-direction: column;

}
.percentage{
  color: #D5873A;
}
.submit-button {
  padding: 12px 24px;
  background: #2f57a7;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 5px;
}

.submit-button:hover {
  background: #1a3d7d;
  transform: translateY(-1px);
}

.upload-container {
  border: 2px dashed rgb(162, 162, 162);
  padding: 20px;
  border-radius: 8px;
  height: 50%;
  width: 200px;
}

.upload-button {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 6px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
  height: 90%;
  width: 180px;
}

.upload-button:hover {
  background: #e1e7f0;
}

.upload-icon {
  font-size: 18px;
}

.upload-success {
  color: #4CAF50;
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 8px;
  margin-left:20px
}

.success-icon {
  color: #4CAF50;
  font-weight: bold;
}
.success-icon:hover {
  text-decoration: underline;
  
}
.submit-icon {
  font-size: 18px;
}
.attachment-container {
  width: 100%;
}
.no-attachment-img {
  width: 90px;
  margin: 0;
  opacity: 0.7;
}
.content-card{
  background:#F9F9F9;
  padding: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin: 20px;
}
.inline{
  display:flex;
  display: flex;
  align-items:flex-end;
  justify-content: space-between;
  flex-direction: row;
}

</style>